<?php
/**
 * Created by PhpStorm.
 * User: laowang
 * Date: 2018/1/11
 * Time: 下午4:59
 */

namespace app\home\controller;
use app\home\model\WechatUser;
use app\home\model\Test as TestModel;
use app\home\model\Fenxiao;
use app\home\model\Stage;
use app\home\model\Gate;
use think\Db;

/**
 * Class Test
 * @package app\home\controller
 *  测试提交
 */
class Test extends Base
{
    /**
     * 首页
     */
    public function index(){
        $userId = session('userId');
        $this->jssdk();
        $User = WechatUser::where(['openid' => $userId])->find();
        if ($User['review_status'] == 0 || $User['role'] ==1 || $User['subscribe'] == 0){
            $this->redirect('Test/null');
        }
        if(IS_POST){
            //前台post提交表单
            $data = input('post.');
            $data['openid'] = $userId;
            $data['test_time'] = strtotime($data['test_time']);
            $data['create_time'] = time();
            $result = Fenxiao::where(array('paper_id'=>$data['code']))->find();
            if(empty($result)){
                return $this->error('试卷编码输入有误~请重试！');
            }
            $Model = new TestModel();
            $res = $Model->where(['openid' => $userId,'code' => $data['code']])->find();
            if ($res){
                $result = $Model->update($data,['id' => $res['id']]);
            }else{
                WechatUser::where('openid',$userId)->setInc('score',1);
                $result = $Model->save($data);
            }
            if($result){
                return $this->success("提交成功");
            }else{
                return $this->error($Model->getError());
            }
        }else{
            return $this->fetch();
        }
    }
    //测试提交 详情
    public function detail(){
        $id = input('id/d');
        $openid = input('openid',session('userId'));
        $User = WechatUser::where(['openid' => $openid])->find();
        if ($User['review_status'] == 0 || $User['subscribe'] == 0){
            $this->redirect('Test/null');
        }
        $msg = TestModel::where(['id' => $id])->find();
        if (empty($msg)){
            $this->redirect('Test/del');
        }
        $rank = TestModel::where(['code' => $msg['code'],'status' => 0])->order('score','desc')->select();
        $msg['rank'] = '暂无';
        foreach ($rank as $key => $value){
            if ($value['openid'] == $msg['openid']){
                $msg['rank'] = $key+1;
            }
        }
        $msg['class'] = '**数据缺失**';  // 阶段
        $msg['class1'] = '**数据缺失**';  // 大类
        $msg['class2'] = '**数据缺失**';  // 项目大类
        $msg['class3'] = '**数据缺失**';  // 一级项目
        $msg['class4'] = '**数据缺失**';  // 二级项目
        $paper = Fenxiao::where('paper_id',$msg['code'])->find();
        if ($paper){
            $stage = Stage::where('id',$paper['stage_id'])->value('name');
            $msg['class'] = iconv("gbk", "utf-8//ignore", $stage);  // 阶段
            $gate = Gate::where('id',$paper['project_id'])->field('class1,class2,class3,class4')->find();
            $msg['class1'] = iconv("gbk", "utf-8//ignore", $gate['class1']);  // 大类
            $msg['class2'] = iconv("gbk", "utf-8//ignore", $gate['class2']);  // 项目大类
            $msg['class3'] = iconv("gbk", "utf-8//ignore", $gate['class3']);  // 一级项目
            $msg['class4'] = iconv("gbk", "utf-8//ignore", $gate['class4']);  // 二级项目
        }
        $this->assign('msg',$msg);
        return $this ->fetch();
    }
    //扫码方法
    public function scan(){
        $code = input('code');
        // 数据库
        $dbConfig = 'mysql://weixin:lby32158@116.62.59.221:3306/managent_18#gbk';
        $sql = "SELECT title FROM oa_test_paper WHERE paper_id = '".trim($code)."'";
        $result = Db::connect($dbConfig)->query($sql);
        if(!empty($result)){
            return array('status'=>1,'code'=>$code,'title' => iconv("gbk", "utf-8//ignore", $result[0]['title']));
        }else{
            return array('status'=>2,'code'=>null);
        }
    }
    // 暂无权限
    public function null(){
        return $this->fetch();
    }
    // 数据不存在
    public function del(){
        return $this->fetch();
    }
    // 记录列表页面
    public function testlist(){
        $userId = input('openid',session('userId'));
        $User = WechatUser::where(['openid' => $userId])->find();
        if ($User['review_status'] == 0  || $User['role'] ==1 || $User['subscribe'] == 0){
            $this->redirect('Test/null');
        }
        if(IS_POST){
            $year = input('year');
            //只选取年份，默认为所有
            $info = array(
                "FROM_UNIXTIME(create_time,'%Y')"  => $year,
                "openid" => $userId,
                'status' => 0
            );
            $all = TestModel::where($info)->order('id desc')->select();
            //重组用key值分组
            $list = array();
            foreach($all as $value){
                $value['day'] = date("d",$value['create_time']);
                $value['time'] = date("m-d",$value['test_time']);
                $value['class'] = '暂无';  // 阶段
                $value['class2'] = '暂无';  // 项目大类
                $value['class4'] = '暂无';  // 二级项目
                $paper = Fenxiao::where('paper_id',$value['code'])->find();
                if ($paper){
                    $stage = Stage::where('id',$paper['stage_id'])->value('name');
                    $value['class'] = iconv("gbk", "utf-8//ignore", $stage);  // 阶段
                    $gate = Gate::where('id',$paper['project_id'])->field('class1,class2,class3,class4')->find();
                    $value['class2'] = iconv("gbk", "utf-8//ignore", $gate['class2']);  // 项目大类
                    $value['class4'] = iconv("gbk", "utf-8//ignore", $gate['class4']);  // 二级项目
                }
                $k = date("n",$value['create_time']);
                $list[$k][] = $value;
            }
            return $this->success('','',$list);
        }else{
            //获取全部共同数据年份
            $years = TestModel::all(function($query){
                $query->group("FROM_UNIXTIME(create_time,'%Y')")->field("FROM_UNIXTIME(create_time,'%Y') as year");
            });
            if (empty($years)){
                $years = [0 => ['year' => date('Y')]];
            }
            $this->assign('years',$years);

            //当前年份初始化数据
            $nowyear = date('Y',time());
            $info = array(
                "FROM_UNIXTIME(create_time,'%Y')"  => $nowyear,
                "openid" => $userId,
                'status' => 0
            );
            $lists = TestModel::where($info)->order('id desc')->select();
            //重组用key值分组
            $list = array();
            foreach($lists as $value){
                $k = date("n",$value['create_time']);
                $value['class'] = '暂无';  // 阶段
                $value['class2'] = '暂无';  // 项目大类
                $value['class4'] = '暂无';  // 二级项目
                $paper = Fenxiao::where('paper_id',$value['code'])->find();
                if ($paper){
                    $stage = Stage::where('id',$paper['stage_id'])->value('name');
                    $value['class'] = iconv("gbk", "utf-8//ignore", $stage);  // 阶段
                    $gate = Gate::where('id',$paper['project_id'])->field('class1,class2,class3,class4')->find();
                    $value['class2'] = iconv("gbk", "utf-8//ignore", $gate['class2']);  // 项目大类
                    $value['class4'] = iconv("gbk", "utf-8//ignore", $gate['class4']);  // 二级项目
                }
                $list[$k][] = $value;
            }
            krsort($list);
            $this->assign('list',$list);
            $this->assign('userid',$userId);
            return $this->fetch();
        }
    }
}